<template>
  <div class="app-container">
    <!-- 侧边栏 -->
    <el-menu
      :default-active="activeMenu"
      class="sidebar-menu"
      :collapse="isCollapse"
      background-color="#304156"
      text-color="#bfcbd9"
      active-text-color="#409EFF"
      router
      unique-opened
    >
      <!-- Logo区域 -->
      <div class="sidebar-logo">
        <img src="../assets/logo.png" alt="logo" v-if="!isCollapse">
        <div class="logo-text" v-if="!isCollapse">排队叫号系统</div>
        <img src="../assets/logo-mini.png" alt="logo" v-else>
      </div>
      
      <!-- 动态菜单项 -->
      <template v-for="item in menuItems" :key="item.path">
        <!-- 判断用户是否有权限查看此菜单 -->
        <template v-if="hasPermission(item.roles)">
          <!-- 有子菜单的情况 -->
          <el-sub-menu v-if="item.children && item.children.length" :index="item.path">
            <template #title>
              <el-icon>
                <component :is="item.icon"></component>
              </el-icon>
              <span>{{ item.title }}</span>
            </template>
            
            <template v-for="child in item.children" :key="child.path">
              <el-menu-item v-if="hasPermission(child.roles)" :index="child.path">
                {{ child.title }}
              </el-menu-item>
            </template>
          </el-sub-menu>
          
          <!-- 没有子菜单的情况 -->
          <el-menu-item v-else :index="item.path">
            <el-icon>
              <component :is="item.icon"></component>
            </el-icon>
            <template #title>{{ item.title }}</template>
          </el-menu-item>
        </template>
      </template>
    </el-menu>
    
    <!-- 主内容区 -->
    <div class="main-container">
      <!-- 顶部头 -->
      <div class="main-header">
        <div class="header-left">
          <el-button 
            type="text" 
            @click="toggleSidebar"
            :icon="isCollapse ? 'Expand' : 'Fold'"
            style="color: #606266;"
          >
            <el-icon v-if="isCollapse"><Expand /></el-icon>
            <el-icon v-else><Fold /></el-icon>
          </el-button>
          <breadcrumb />
        </div>
        <div class="header-right">
          <el-dropdown @command="handleCommand">
            <span class="user-dropdown">
              <img class="user-avatar" src="../assets/avatar.jpg" alt="avatar">
              <span class="username">{{ username }}</span>
              <el-icon><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="password">修改密码</el-dropdown-item>
                <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      
      <!-- 页面内容 -->
      <div class="main-content">
        <router-view v-slot="{ Component }">
          <transition name="fade" mode="out-in">
            <keep-alive :include="cachedViews">
              <component :is="Component" />
            </keep-alive>
          </transition>
        </router-view>
      </div>
    </div>
    
    <!-- 修改密码对话框 -->
    <el-dialog title="修改密码" v-model="passwordDialogVisible" width="500px" center>
      <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="100px">
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleChangePassword">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { ArrowDown, DataLine, List, Briefcase, PieChart, Setting, Expand, Fold } from '@element-plus/icons-vue'

export default {
  name: 'Layout',
  components: {
    ArrowDown,
    DataLine,
    List,
    Briefcase,
    PieChart,
    Setting,
    Expand,
    Fold
  },
  setup() {
    const router = useRouter()
    const route = useRoute()
    
    // 侧边栏状态
    const isCollapse = ref(false)
    const toggleSidebar = () => {
      isCollapse.value = !isCollapse.value
    }
    
    // 获取当前激活菜单
    const activeMenu = computed(() => {
      return route.path
    })
    
    // 用户信息
    const userInfo = ref({
      username: '',
      role: ''
    });
    
    // 获取用户信息
    onMounted(() => {
      const userInfoStr = localStorage.getItem('userInfo');
      if (userInfoStr) {
        try {
          const parsedInfo = JSON.parse(userInfoStr);
          userInfo.value = parsedInfo;
        } catch (e) {
          console.error('解析用户信息失败:', e);
        }
      }
    });
    
    // 计算用户名显示
    const username = computed(() => {
      if (userInfo.value.role === 'superadmin') {
        return '超级管理员';
      } else if (userInfo.value.role === 'admin') {
        return '管理员';
      } else if (userInfo.value.role === 'operator') {
        return '窗口操作员';
      }
      return userInfo.value.username || '未知用户';
    });
    
    // 判断当前用户是否有权限查看某个菜单
    const hasPermission = (roles) => {
      if (!roles || roles.length === 0) {
        return true;
      }
      return roles.includes(userInfo.value.role);
    };
    
    // 菜单配置
    const menuItems = reactive([
      {
        path: '/dashboard',
        title: '数据大盘',
        icon: 'DataLine',
        roles: ['admin', 'superadmin']
      },
      {
        path: '/queue',
        title: '队列管理',
        icon: 'List',
        roles: ['admin', 'superadmin'],
        children: [
          {
            path: '/queue/list',
            title: '队列列表',
            roles: ['admin', 'superadmin']
          },
          {
            path: '/queue/window',
            title: '窗口管理',
            roles: ['admin', 'superadmin']
          }
        ]
      },
      {
        path: '/business',
        title: '业务管理',
        icon: 'Briefcase',
        roles: ['admin', 'superadmin'],
        children: [
          {
            path: '/business/type',
            title: '业务类型',
            roles: ['admin', 'superadmin']
          }
        ]
      },
      {
        path: '/statistics',
        title: '业务统计',
        icon: 'PieChart',
        roles: ['admin', 'superadmin'],
        children: [
          {
            path: '/statistics/daily',
            title: '日常统计',
            roles: ['admin', 'superadmin']
          },
          {
            path: '/statistics/report',
            title: '统计报表',
            roles: ['admin', 'superadmin']
          }
        ]
      },
      {
        path: '/system',
        title: '系统管理',
        icon: 'Setting',
        roles: ['admin', 'superadmin'],
        children: [
          {
            path: '/system/user',
            title: '用户管理',
            roles: ['superadmin']
          },
          {
            path: '/system/role',
            title: '角色管理',
            roles: ['superadmin']
          },
          {
            path: '/system/config',
            title: '系统配置',
            roles: ['admin', 'superadmin']
          }
        ]
      }
    ]);
    
    // 缓存的视图
    const cachedViews = ref(['Dashboard', 'QueueList'])
    
    // 处理下拉菜单操作
    const handleCommand = (command) => {
      if (command === 'logout') {
        ElMessageBox.confirm('确定要退出登录吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 清除所有登录信息
          localStorage.removeItem('token')
          localStorage.removeItem('tokenHead')
          localStorage.removeItem('expireTime')
          localStorage.removeItem('userInfo')
          
          router.push('/login')
          ElMessage.success('退出登录成功')
        }).catch(() => {})
      } else if (command === 'password') {
        passwordDialogVisible.value = true
      }
    }
    
    // 密码表单
    const passwordDialogVisible = ref(false)
    const passwordFormRef = ref(null)
    const passwordForm = reactive({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
    
    // 密码表单校验规则
    const passwordRules = {
      oldPassword: [
        { required: true, message: '请输入旧密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== passwordForm.newPassword) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }
    
    // 处理修改密码
    const handleChangePassword = () => {
      passwordFormRef.value.validate((valid) => {
        if (valid) {
          ElMessage.success('密码修改成功')
          passwordDialogVisible.value = false
          
          // 清空表单
          passwordForm.oldPassword = ''
          passwordForm.newPassword = ''
          passwordForm.confirmPassword = ''
        }
      })
    }
    
    return {
      isCollapse,
      toggleSidebar,
      activeMenu,
      username,
      cachedViews,
      handleCommand,
      passwordDialogVisible,
      passwordFormRef,
      passwordForm,
      passwordRules,
      handleChangePassword,
      menuItems,
      hasPermission,
      userInfo
    }
  }
}
</script>

<style scoped>
.app-container {
  height: 100%;
  width: 100%;
  display: flex;
  overflow: hidden;
}

.sidebar-menu {
  height: 100%;
  border-right: none;
  position: relative;
  transition: width 0.3s;
  width: 220px;
}

.sidebar-menu.el-menu--collapse {
  width: 64px;
}

.sidebar-logo {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #2b3b4e;
  padding: 10px;
  box-sizing: border-box;
}

.sidebar-logo img {
  height: 32px;
}

.logo-text {
  color: #ffffff;
  font-size: 16px;
  font-weight: bold;
  margin-left: 10px;
}

.main-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
}

.main-header {
  height: 60px;
  padding: 0 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ebeef5;
  background-color: #fff;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-right {
  display: flex;
  align-items: center;
}

.user-dropdown {
  cursor: pointer;
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-right: 8px;
}

.username {
  font-size: 14px;
  color: #606266;
  margin-right: 5px;
}

.main-content {
  flex: 1;
  padding: 20px;
  overflow: auto;
  background-color: #f0f2f5;
}
</style> 